import { createWebHistory, createRouter } from "vue-router"
import UserManage from "../view/UserManage.vue"
import RoleManage from "../view/RoleManage.vue"
import Login from "../view/login.vue"
import IndexView from "../view/IndexView.vue"
import ProcedureManage from "../view/ProcedureManage.vue"
import CategoryManage from "../view/IdentifyManage/CategoryManage.vue"
import ProcessManage from "../view/ProcessManage.vue"
import RuleManage from "../view/IdentifyManage/RuleManage.vue"
import CodingDevice from "../view/IdentifyManage/CodingDevice.vue"
import WarehouseManage from "../view/IdentifyManage/WarehouseManage.vue"
import TaskManagement from "../view/TaskManagement.vue"
import ServiceManage from "../view/ServiceManage.vue"
import { routePermissions } from "../utils/permission.ts"
import { getUserRole } from '../api/user';
import DetailInfo from "../view/DetailInfo.vue"

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/login',
      component: Login // 登录页，无布局
    },
    {
      path: '/', // 父路由：渲染布局（IndexView）
      component: IndexView,
      meta: { requiresAuth: true }, // 标记需要登录
      children: [
        //{ path: '', redirect: 'user' }, // 根路径重定向到 /user
        { path: '/user', component: UserManage },
        { path: '/role', component: RoleManage },
        { path: '/process', component: ProcessManage },
        { path: '/produce', component: ProcedureManage },
        {
          path: '/identify', children: [
            { path: '/identify/category', component: CategoryManage },
            { path: '/identify/rule', component: RuleManage },
            { path: '/identify/device', component: CodingDevice },
            { path: '/identify/warehouse', component: WarehouseManage },
          ]
        },
        { path: '/task', component: TaskManagement },
        { path: '/service', component: ServiceManage },
        { path: '/detailinfo', component: DetailInfo },
      ]
    }
  ]
})

// 导航守卫：处理登录权限
router.beforeEach(async (to, from, next) => {
  const isLogin = !!localStorage.getItem('token');
  const role = Number(localStorage.getItem('role'));
  if (to.path === '/') {
    // 1. 如果未登录：根路径直接跳登录页（或保持默认，根据需求调整）
    if (!isLogin) {
      next('/login');
      return;
    }
    // 2. 如果已登录：获取用户角色，匹配默认跳转路径
    let redirectPath = '/';
    switch (role) {
      case 0:
        redirectPath = '/user';
        break;
      case 1:
        redirectPath = '/process';
        break;
      case 2:
        redirectPath = '/identify/device';
        break;
      case 3:
        redirectPath = '/task';
        break;
      default:
        redirectPath = '/';
    }

    next(redirectPath);
    return;
  }
  if (to.path === '/login') {
    next();
    return;
  }
  next();
  // if (to.meta.requiresAuth) {
  //   if (!isLogin) {
  //     next('/login');
  //     return;
  //   }

  //   // 用接口获取角色替换localStorage
  //   const userRole = await getUserRole();
  //   if (userRole === null) {
  //     next('/login');
  //     return;
  //   }

  //   // 权限判断逻辑保持不变
  //   if (routePermissions[to.path]?.includes(userRole) ||
  //     Object.keys(routePermissions).some(path =>
  //       to.path.startsWith(path) && routePermissions[path]?.includes(userRole)
  //     )) {
  //     next();
  //   } else {
  //     next('/login');
  //   }
  // } else {
  //   next();
  // }
});


export default router